import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/brands/brands_details_page.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:gzmall_app/store/store_detail_page.dart';
import 'package:gzmall_app/model/brand.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';

class BrandListPage extends StatefulWidget {
  String title = '';
  String params;

  BrandListPage({this.title, this.params});

  @override
  State<StatefulWidget> createState() =>
      BrandListPageState(title: this.title, params: this.params);
}

class BrandListPageState extends State<BrandListPage> {
  String title = '';
  String params;

  List<Brand> _brandList = [];

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  BrandListPageState({this.title, this.params});

  @override
  void initState() {
    super.initState();
    _getBrand(1);
  }

  @override
  Widget build(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: ListView.builder(
          itemCount: _brandList.length,
          itemBuilder: (BuildContext context, int index) {
            Brand _brand = _brandList[index];
            return _getView(_brand, index);
          }),
      showEmpty: _showEmpty,
      onReload: () {
        _getBrand(1);
      },
    );
    return Scaffold(
      appBar: _createAppBar(),
      body: Container(
        color: ColorCommon.grey5,
        child: _refreshListView,
      ),
    );
  }

  Widget _getView(Brand brand, int i) {
    double width = (MediaQuery.of(context).size.width - 20 - 40) / 3;
    List<Widget> _subWidget = [];
    if (brand.spus != null && brand.spus.length > 0) {
      for (var i = 0; i < brand.spus.length; i++) {
        if (i < 3) {
          _subWidget.add(InkWell(
            child: _getSubView(
                brand.spus[i],
                width,
                (i == 1
                    ? EdgeInsets.only(left: 10.0, right: 10.0)
                    : EdgeInsets.zero)),
            onTap: () {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new GoodsDetailsPage(productId: brand.spus[i].id);
              }));
            },
          ));
        }
      }
    }
    return Container(
        margin: EdgeInsets.only(
            left: 10.0, right: 10.0, top: (i == 0 ? 10.0 : 0.0), bottom: 10.0),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(5.0))),
        child: Column(
          children: <Widget>[
            brand != null && brand.bigAvatar != null
                ? InkWell(
                    onTap: () {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return new BrandsDetailsPage(id: brand.id);
                      }));
                    },
                    child: Container(
                      height: 150.0,
                      width: MediaQuery.of(context).size.width,
                      margin: const EdgeInsets.only(bottom: 10.0),
                      alignment: Alignment.centerLeft,
                      decoration: new BoxDecoration(
                        borderRadius:
                            BorderRadius.all(const Radius.circular(5.0)),
                        image: new DecorationImage(
                            image:
                                new CachedNetworkImageProvider(brand.bigAvatar),
                            fit: BoxFit.fill),
                      ),
                    ),
                  )
                : Container(),
            _subWidget != null && _subWidget.length > 0
                ? new Container(
                    padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: _subWidget,
                    ),
                  )
                : Container(),
          ],
        ));
  }

  Widget _getSubView(Product p, double width, EdgeInsetsGeometry margin) {
    return Container(
      child: new Column(
        children: <Widget>[
          new Container(
            width: width,
            height: width,
            margin: margin,
            decoration: new BoxDecoration(
              borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(5.0),
                  topRight: Radius.circular(5.0)),
              image: new DecorationImage(
                image: new CachedNetworkImageProvider(p.avatar),
                fit: BoxFit.fill,
              ),
            ),
          ),
          new Container(
            padding: const EdgeInsets.only(top: 4.0, bottom: 10.0),
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Text(
                  p.name,
                  style: TextStyle(fontSize: 12.0, color: ColorCommon.black1),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text(this.title),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getBrand(1);
    } else {
      _getBrand(_curPage + 1);
    }
  }

  _getBrand(int page) {
    bool isGetNew = page == 1;
    Map<String, Object> params = {"page": page.toString()};
    if (this.params != null && this.params.isNotEmpty) {
      Map<String, dynamic> otherParams = json.decode(this.params);
      params.addAll(otherParams);
    }
    NetUtil.get(
        context,
        Api.brands,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Brand.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _brandList = _dataList;
            } else {
              _brandList.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty =
                isGetNew && (_brandList == null || _brandList.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
